<?php
namespace app\controller;

use app\BaseController;
use app\controller\model\SPay;
use app\controller\model\Tables;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class Orders extends BaseController
{
    protected $getpath="";
    protected $gobaluser="";
    protected $tables;
	protected $notify = "https://gas.zhissf.com/Notify";
    public function __construct($check=true){
		if($check){
			checkuser();
			$this->gobaluser=Session::get("uid");
		}
        $this->tables = new Tables();
    }
    public function index(){
	    $admin = r_user($this->gobaluser);
	    $isAdmin=true;
	    $serviceOption='';
	    $classes = new \app\controller\model\Classes();
	    if($admin['ctype']==2){
		    $isAdmin=false;
		    $serviceOption = $classes->rMyGasToOption(0,$admin['serviceIDS'])[0];
	    }
        return view("orders/list")->assign(['supplier'=>$classes->rSupplierToOption()[0],'isAdmin'=>$isAdmin,'serviceOption'=>$serviceOption]);
    }
	public function pushService(){
	    $log = new \app\Log("push");
		$id = request()->param("id");
		$order=DB::name($this->tables->serviceOrder)->where("id",$id)->find();
		if($order['reOrder']!=2 && $order['reOrder']!=-1)echojson([],1,"ID错误");//订单状态错误
		$serviceModel = new Service();
		$pushRe = $serviceModel->pushService($order['serviceID'],'order',$order['service_no']);
		if($pushRe===true && $order['reOrder']==2){
			DB::name($this->tables->serviceOrder)->where("id",$order['id'])->update(['reOrder'=>3]);
		}
		$log->write(['order'=>$order,'pushRe'=>$pushRe]);
		if(!$pushRe===true)echojson([],1,'推送失败见日志');
		echojson();
	}
    public function indexService(){
		$admin = r_user($this->gobaluser);
		$isAdmin=true;
	    $serviceOption='';
	    $classes = new \app\controller\model\Classes();
		if($admin['ctype']==1){
			$isAdmin=false;
			$serviceOption = $classes->rMyServiceToOption(0,$admin['serviceIDS'])[0];
		}
        return view("orders/listService")->assign(['supplier'=>$classes->rSupplierToOption()[0],'isAdmin'=>$isAdmin,'serviceOption'=>$serviceOption]);
    }
    public function groups(){
        return (new Classes())->classes(1);
    }
    public function authruleedit(){
        return (new Classes())->authruleedit();
    }
	public function serviceOrderDel(){
		//取消已确认的订单
		$id = request()->param("id");
		$password = request()->param("password");
		$admin = r_user($this->gobaluser);
		if(md5($password) != $admin['password2'])echojson([],1,'操作密码错误');
		$order=DB::name($this->tables->serviceOrder)->where("id",$id)->find();
		if($order['status']!=1)echojson([],1,"ID错误");//订单状态错误
		//上游供应商取消订单
		$supplierModel = new \app\controller\model\Supplier($order['supplierID']);
		$supplierModel->cancelOrder($order);
		//上游取消成功
		if($order['status']==1){
			DB::name($this->tables->serviceOrder)->where("id",$order['id'])->update(['reOrder'=>4]);
			echojson([],0,'待上游审核');
		}
		$this->serviceOrderDelRePay($order);
	}
	public function serviceOrderDelRePay($order,$ret=true){

		$setOrder = DB::name($this->tables->serviceOrder)->where("id",$order['id'])->update(['status'=>-1,'cancelTime'=>nowTime(),'reOrder'=>2,'reConfirmTime'=>nowTime()]);
		if(!$setOrder)echojson([],1,'取消订单失败');//取消订单失败
		//本地取消成功 扣费
		$serviceModel = new Service(false);
		$addLog = $serviceModel->rechargeAdmin2Save(['userID'=>$order['serviceID'],'img1'=>'null','amount'=>$order['realPrice'],'pays'=>283,'content'=>"服务商订单 ".$order['id']." 退款"],true);
		if(!$addLog)echojson([],1,'日志写入失败');
		//推送退单成功
		$pushRe = $serviceModel->pushService($order['serviceID'],'order',$order['service_no']);
		if($pushRe===true){
			DB::name($this->tables->serviceOrder)->where("id",$order['id'])->update(['reOrder'=>3]);
		}
		 if ($ret)
            echojson();
        else echojson([],200,"退款成功！");
	}
	public function ordersDel(){
		$id = request()->param("id");
		$password = request()->param("password");
		$admin = r_user($this->gobaluser);
		if(md5($password)!=$admin['password2'])echojson([],1,'操作密码错误');
		$re = DB::name($this->tables->orders)->where("id",$id)->find();
		if(!$re){echojson([],1,'ID错误');}
		if($re['status']<3)echojson([],1,'未支付');
		if($re['reOrder']==2)echojson([],1,'已退款');

		$supplierModel = new \app\controller\model\Supplier($re['supplierID']);
		$supplierModel->cancelOrder($re);//如果错误 会自动回滚事务 这里不用再判断

		if($re['status']==4){
			DB::name($this->tables->orders)->where("id",$re['id'])->update(['reOrder'=>3]);
			echojson([],0,'待上游审核');
		}
		$this->ordersDelRePay($re);

	}
	public function ordersDelRePay($re,$ret=true){
		if($re['reMoney']<=0)$re['reMoney']=$re['payPrice'];
		$payModel = new SPay();
		$re_no = getOrderNo(); //第三方支付要求退还要有退款新的退款订单号re_no
		DB::name($this->tables->orders)->where("id",$re['id'])->update(['re_no'=>$re_no]);
		$order = $payModel->refund($re['reMoney'],$re['order_no'],$re_no,'',$this->notify);
		if(isset($order['resultCode']) && $order['resultCode']=='SUCCESS'){
			$re = DB::name($this->tables->orders)->where("id",$re['id'])->update(['status'=>-4,'reOrder'=>2,'content'=>$re['content']."->原状态：".$re['status']]);
			if(!$re){echojson([],1,'删除失败');}
		    if ($ret)
                echojson();
            else
                echojson([],200,"退款成功");
		}
		echojson([],1,'退款失败');
	}
	public function orderServiceDelNo(){
		lock();
		$id = request()->param("id");
		$content = request()->param("content");
		$re = DB::name($this->tables->serviceOrder)->where("id",$id)->find();
		if(!$re){echojson([],1,'订单ID错误');}
		if($re['reOrder']!=1){
			echojson([],1,'非待退款状态');
		}
		if($content==''){echojson([],1,'原因必填');}
		$upRe = DB::name($this->tables->serviceOrder)->where("id",$id)->update(['reOrder'=>-1,'reContent'=>$re['reContent']." 回复：".$content." 回复结束"]);
		if(!$upRe){echojson([],1,'更新失败');}
		$serviceModel = new Service();
		$pushRe = $serviceModel->pushService($re['serviceID'],'order',$re['service_no']);
		if($pushRe===true) echojson();
		echojson([],1,$pushRe);
	}

    public function ordersDelNo(){
        $id = request()->param("id");
        $content = request()->param("content");
        $re = DB::name($this->tables->orders)->where("id",$id)->find();
        if(!$re){echojson([],1,'ID错误');}
        if($re['reOrder']!=1){
            echojson([],1,'非待退款状态');
        }
	    if($content==''){echojson([],1,'原因必填');}
        $re = DB::name($this->tables->orders)->where("id",$id)->update(['reOrder'=>-1,'content'=>$re['content']." 回复：".$content]);
        if(!$re){echojson([],1,'成功');}
        echojson();
    }
    public function postGoodsSave(){
        $id = request()->param("id");
        $orderNo = request()->param("orderNo");
        $re = DB::name($this->tables->orders)->where("id",$id)->find();
        if(!$re){echojson([],1,'ID错误');}
        if($orderNo==''){echojson([],1,'单号错误');}
        if($re['status']!=1){
            echojson([],1,'不在待发货状态');
        }
        $re = DB::name($this->tables->orders)->where("id",$id)->update(['status'=>2,'expressNo'=>$orderNo,'expressTime'=>nowTime()]);
        if(!$re){echojson([],1,'发货成功');}
        echojson();
    }
    public function setEnd(){
        $id = request()->param("id");
        $re = r_one($this->tables->orders,"id=$id");
        if(!$re){echojson([],1,'ID错误');}
        $re = DB::name($this->tables->orders)->where("id",$id)->update(['status'=>3,'content'=>$re['content'].$this->gobaluser."->设置订单完成：".nowTime().";"]);
        if(!$re){echojson([],1,'删除失败');}
        echojson();
    }
    public function serviceUsersList($return =false,$postLimit=0){
	    $admin = r_user($this->gobaluser);
	    $isAdmin=true;
	    if($admin['ctype']==1)$isAdmin=false;
        $page = request()->param("page");
        $uid = request()->param("uid");
        $gasID = request()->param("gasID");
        $service_no = request()->param("service_no");
        $serviceID = request()->param("serviceID");
        $supplier_no = request()->param("supplier_no");
        $supplierID = request()->param("supplierID");
        $startTime = request()->param("startTime");
        $endTime = request()->param("endTime");
        $status = request()->param("status");
        $reOrder = request()->param("reOrder");
        $limit = request()->param("limit");
        $sql = DB::name($this->tables->serviceOrder)->field("a.*,b.name,c.title as serviceTitle")->alias("a")->leftJoin($this->tables->gas." b","a.gasID=b.id")->leftJoin($this->tables->service." c","a.serviceID = c.id");
        $limit < 10 ? $limit = 10 : '';
        if($postLimit>0){
            $limit = $postLimit ;
        }
        $page<1?$page=1:'';
		if($isAdmin==false){
			$sql = $sql->whereIn("a.serviceID",$admin['serviceIDS']);
		}
        if($gasID>0){
            $sql = $sql->where("a.gasID",$gasID);
        }
        if($service_no != ''){
            $sql = $sql->where("a.service_no",$service_no);
        }
        if($supplier_no != ''){
            $sql = $sql->where("a.supplier_no",$supplier_no);
        }
        if($supplierID>0){
            $sql = $sql->where("a.supplierID",$supplierID);
        }

        if($serviceID>0){
            $sql = $sql->where("a.serviceID",$serviceID);
        }

        if($reOrder!=''){
            $sql = $sql->where("a.reOrder",$reOrder);
        }

        if($startTime!='' && $endTime!=''){
            $sql=$sql->where("a.addTime",">=",date("Y-m-d 00::00:00",strtotime($startTime)))->where("a.addTime","<=",date("Y-m-d 23:59:59",strtotime($endTime)));
        }
        if($status==''){

        }else{
            $sql = $sql->where("a.status",$status);
        }
        $count = (clone $sql)->count();
        $pages = ceil($count / $limit);
        $pages < 1 ? $pages = 1 : '';
        $page > $pages ? $page = $pages : '';
        $res = $sql->order("a.id desc")->limit(($page - 1) * $limit, $limit)->select();
		$chasses = new \app\controller\model\Classes();
		$supplier = $chasses->rSupplierToOption()[2];
	    $res =$res->all();
	    foreach ($res as &$v){
			$v['supplier']=rclasstitle($supplier,$v['supplierID']);
	    }
        if($return){
            return [$res, 0, '', $count];
        }
        pagejson($res, 0, '', $count);
    }
    public function usersList($return =false,$postLimit=0){
	    $admin = r_user($this->gobaluser);
	    $isAdmin=true;
	    if($admin['ctype']==2)$isAdmin=false;//加油站管理员
        $page = request()->param("page");
        $uid = request()->param("uid");
        $gasID = request()->param("gasID");
        $order_no = request()->param("order_no");
        $supplierID = request()->param("supplierID");
        $startTime = request()->param("startTime");
        $endTime = request()->param("endTime");
        $status = request()->param("status");
        $limit = request()->param("limit");
	    $reOrder = request()->param("reOrder");
        $sql = DB::name($this->tables->orders)->field("a.*,b.name")->alias("a")->leftJoin($this->tables->gas." b","a.gasID=b.id");
        $limit < 10 ? $limit = 10 : '';
        if($postLimit>0){
            $limit = $postLimit ;
        }
        $page<1?$page=1:'';
        if($uid>0){
            $sql = $sql->where("b.uid",$uid);
        }
	    if($isAdmin==false){
		    $sql = $sql->whereIn("a.gasID",$admin['serviceIDS']);
	    }
        if($gasID>0){
            $sql = $sql->where("a.gasID",$gasID);
        }
        if($reOrder>0){
            $sql = $sql->where("a.reOrder",$reOrder);
        }
        if($order_no!=''){
            $sql = $sql->where("a.order_no",$order_no);
        }
        if($supplierID>0){
            $sql = $sql->where("a.supplierID",$supplierID);
        }

        if($startTime!='' && $endTime!=''){
            $sql=$sql->where("a.addTime",">=",date("Y-m-d 00::00:00",strtotime($startTime)))->where("a.addTime","<=",date("Y-m-d 23:59:59",strtotime($endTime)));
        }
        if($status==''){
            $sql=$sql->where("a.status",">=",3);
        }else{
            $sql = $sql->where("a.status",$status);
        }
        $count = (clone $sql)->count();
        $pages = ceil($count / $limit);
        $pages < 1 ? $pages = 1 : '';
        $page > $pages ? $page = $pages : '';
        $res = $sql->order("a.id desc")->limit(($page - 1) * $limit, $limit)->select();
		$chasses = new \app\controller\model\Classes();
		$supplier = $chasses->rSupplierToOption()[2];
	    $res =$res->all();
	    foreach ($res as &$v){
			$v['supplier']=rclasstitle($supplier,$v['supplierID']);
	    }
        if($return){
            return [$res, 0, '', $count];
        }
        pagejson($res, 0, '', $count);
    }
}
